package Pet.Management.controller;

import Pet.Management.common.Result;
import Pet.Management.domain.entity.TaskNode;
import Pet.Management.service.TaskNodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.HashMap;
import java.util.Optional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@RestController
@RequestMapping("/api/pet-care/orders/{orderId}/task-nodes")
public class TaskNodeController {

    private static final Logger logger = LoggerFactory.getLogger(TaskNodeController.class);

    @Autowired
    private TaskNodeService taskNodeService;

    @GetMapping
    public ResponseEntity<?> getTaskNodes(@PathVariable Long orderId) {
        try {
            List<TaskNode> taskNodes = taskNodeService.getTaskNodesByOrderId(orderId);
            Map<String, Object> response = new HashMap<>();
            response.put("code", 200);
            response.put("msg", "获取任务节点成功");
            response.put("data", taskNodes);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("code", 500);
            response.put("msg", "获取任务节点失败: " + e.getMessage());
            return ResponseEntity.ok(response);
        }
    }

    @PostMapping
    public ResponseEntity<?> createTaskNode(@PathVariable Long orderId, @RequestBody TaskNode taskNode) {
        try {
            taskNode.setOrderId(orderId);
            TaskNode createdNode = taskNodeService.createTaskNode(taskNode);
            Map<String, Object> response = new HashMap<>();
            response.put("code", 200);
            response.put("msg", "创建任务节点成功");
            response.put("data", createdNode);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("code", 500);
            response.put("msg", "创建任务节点失败: " + e.getMessage());
            return ResponseEntity.ok(response);
        }
    }

    @PostMapping("/init")
    public ResponseEntity<?> createInitialTaskNodes(@PathVariable Long orderId, @RequestBody List<TaskNode> taskNodes) {
        try {
            taskNodes.forEach(node -> {
                node.setOrderId(orderId);
                node.setCreateTime(LocalDateTime.now());
                node.setUpdateTime(LocalDateTime.now());
                if (node.getStatus() == null) {
                    node.setStatus(0);
                }
            });
            
            List<TaskNode> savedNodes = taskNodeService.saveAllTaskNodes(taskNodes);
            Map<String, Object> response = new HashMap<>();
            response.put("code", 200);
            response.put("msg", "创建任务节点成功");
            response.put("data", savedNodes);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("code", 500);
            response.put("msg", "创建任务节点失败: " + e.getMessage());
            return ResponseEntity.ok(response);
        }
    }

    @PutMapping("/{nodeId}/status")
    public ResponseEntity<?> updateTaskNodeStatus(
            @PathVariable Long orderId,
            @PathVariable Long nodeId,
            @RequestBody Map<String, Integer> statusUpdate) {
        try {
            TaskNode updatedNode = taskNodeService.updateTaskNodeStatus(nodeId, statusUpdate.get("status"));
            Map<String, Object> response = new HashMap<>();
            response.put("code", 200);
            response.put("msg", "更新任务节点状态成功");
            response.put("data", updatedNode);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("code", 500);
            response.put("msg", "更新任务节点状态失败: " + e.getMessage());
            return ResponseEntity.ok(response);
        }
    }

    @PutMapping("/{nodeId}")
    public ResponseEntity<?> updateTaskNode(
            @PathVariable Long orderId,
            @PathVariable Long nodeId,
            @RequestBody TaskNode taskNode) {
        try {
            taskNode.setId(nodeId);
            taskNode.setOrderId(orderId);
            TaskNode updatedNode = taskNodeService.updateTaskNode(taskNode);
            Map<String, Object> response = new HashMap<>();
            response.put("code", 200);
            response.put("msg", "更新任务节点成功");
            response.put("data", updatedNode);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("code", 500);
            response.put("msg", "更新任务节点失败: " + e.getMessage());
            return ResponseEntity.ok(response);
        }
    }

    @GetMapping("/{id}")
    public Result<TaskNode> getTaskNodeById(@PathVariable Long id) {
        return taskNodeService.getTaskNodeById(id)
                .map(Result::success)
                .orElse(Result.failure("Task node not found"));
    }

    @PostMapping("/batch")
    public Result<List<TaskNode>> createTaskNodes(@RequestBody List<TaskNode> taskNodes) {
        List<TaskNode> createdNodes = taskNodeService.saveAllTaskNodes(taskNodes);
        return Result.success(createdNodes);
    }

    @PutMapping("/{id}/complete")
    public Result<TaskNode> completeTaskNode(@PathVariable Long id) {
        try {
            TaskNode completedNode = taskNodeService.completeTaskNode(id);
            return Result.success(completedNode);
        } catch (RuntimeException e) {
            return Result.failure(e.getMessage());
        }
    }

    @DeleteMapping("/{id}")
    public Result<Void> deleteTaskNode(@PathVariable Long id) {
        if (!taskNodeService.getTaskNodeById(id).isPresent()) {
            return Result.failure("Task node not found");
        }
        taskNodeService.deleteTaskNode(id);
        return Result.success();
    }

    @PostMapping("/{nodeId}/upload")
    public ResponseEntity<?> uploadProof(
            @PathVariable Long orderId,
            @PathVariable Long nodeId,
            @RequestParam(value = "file", required = false) MultipartFile file,
            @RequestParam("title") String title,
            @RequestParam("nodeOrder") Integer nodeOrder,
            @RequestParam("proofDescription") String proofDescription,
            @RequestParam("proofText") String proofText,
            @RequestParam("status") Integer status) {
        
        logger.info("Receiving proof upload for task node: {}, orderId: {}", nodeId, orderId);
        
        try {
            // 先获取现有的任务节点，确保保留所有字段
            Optional<TaskNode> existingNodeOpt = taskNodeService.getTaskNodeById(nodeId);
            if (!existingNodeOpt.isPresent()) {
                logger.warn("Task node not found: {}", nodeId);
                Map<String, Object> response = new HashMap<>();
                response.put("code", 500);
                response.put("msg", "任务节点不存在");
                return ResponseEntity.ok(response);
            }
            
            TaskNode existingNode = existingNodeOpt.get();
            
            // 更新任务节点信息
            existingNode.setTitle(title);
            existingNode.setNodeOrder(nodeOrder);
            existingNode.setProofDescription(proofDescription);
            existingNode.setProofText(proofText);
            existingNode.setStatus(status);
            existingNode.setUpdateTime(LocalDateTime.now());
            
            // 处理图片文件
            if (file != null && !file.isEmpty()) {
                String contentType = file.getContentType();
                String fileName = file.getOriginalFilename();
                long fileSize = file.getSize();
                
                logger.info("File received: name={}, type={}, size={}", fileName, contentType, fileSize);
                
                // 确保是图片类型
                if (contentType != null && contentType.startsWith("image/")) {
                    try {
                        // 获取二进制数据
                        byte[] imageBytes = file.getBytes();
                        
                        if (imageBytes != null && imageBytes.length > 0) {
                            // 直接设置二进制图片数据
                            existingNode.setProofImage(imageBytes);
                            logger.info("Successfully stored binary image data, size: {} bytes", imageBytes.length);
                        } else {
                            logger.warn("Empty image data from file");
                        }
                    } catch (IOException e) {
                        logger.error("Failed to process image file", e);
                        Map<String, Object> response = new HashMap<>();
                        response.put("code", 500);
                        response.put("msg", "处理图片文件失败: " + e.getMessage());
                        return ResponseEntity.ok(response);
                    }
                } else {
                    logger.warn("Uploaded file is not an image: {}", contentType);
                    Map<String, Object> response = new HashMap<>();
                    response.put("code", 500);
                    response.put("msg", "上传的文件不是图片");
                    return ResponseEntity.ok(response);
                }
            } else {
                logger.info("No file uploaded or file is empty");
            }
            
            // 保存更新后的任务节点
            logger.info("Saving task node with updated information");
            TaskNode updatedNode = taskNodeService.updateTaskNode(existingNode);
            logger.info("Task node saved successfully");
            
            Map<String, Object> response = new HashMap<>();
            response.put("code", 200);
            response.put("msg", "上传执行证明成功");
            response.put("data", updatedNode);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            logger.error("Error updating task node", e);
            Map<String, Object> response = new HashMap<>();
            response.put("code", 500);
            response.put("msg", "上传执行证明失败: " + e.getMessage());
            return ResponseEntity.ok(response);
        }
    }

    /**
     * 获取任务节点图片
     */
    @GetMapping("/{id}/image")
    public ResponseEntity<?> getTaskNodeImage(@PathVariable Long id) {
        logger.info("获取任务节点图片: {}", id);
        try {
            Optional<TaskNode> taskNodeOpt = taskNodeService.getTaskNodeById(id);
            if (!taskNodeOpt.isPresent()) {
                logger.warn("任务节点不存在: {}", id);
                return ResponseEntity.notFound().build();
            }
            
            TaskNode taskNode = taskNodeOpt.get();
            byte[] imageData = taskNode.getProofImage();
            
            if (imageData == null || imageData.length == 0) {
                logger.warn("任务节点没有图片数据: {}", id);
                return ResponseEntity.notFound().build();
            }
            
            logger.info("成功获取任务节点图片: {}, 大小: {} 字节", id, imageData.length);
            return ResponseEntity
                    .ok()
                    .contentType(MediaType.IMAGE_JPEG)
                    .body(imageData);
        } catch (Exception e) {
            logger.error("获取任务节点图片失败: " + id, e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("获取图片失败");
        }
    }
} 